/*
 *
 *  *  Copyright (C) 2018  Wanghaobin<463540703@qq.com>
 *
 *  *  AG-Enterprise 企业版源码
 *  *  郑重声明:
 *  *  如果你从其他途径获取到，请告知老A传播人，奖励1000。
 *  *  老A将追究授予人和传播人的法律责任!
 *
 *  *  This program is free software; you can redistribute it and/or modify
 *  *  it under the terms of the GNU General Public License as published by
 *  *  the Free Software Foundation; either version 2 of the License, or
 *  *  (at your option) any later version.
 *
 *  *  This program is distributed in the hope that it will be useful,
 *  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  *  GNU General Public License for more details.
 *
 *  *  You should have received a copy of the GNU General Public License along
 *  *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

package com.kuizii.base.common.oss;


import com.kuizii.base.common.configs.oss.CloudStorageConfig;
import com.qiniu.util.StringUtils;
import com.upyun.RestManager;
import okhttp3.Response;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 七牛云存储
 *
 * @author ace
 */
public class UpyunStorageService extends CloudStorageService {
    private RestManager uploadManager;

    public UpyunStorageService(CloudStorageConfig.UpyunOSSProperty property) {
        this.property = property;
        init(null);
    }

    public CloudStorageConfig.UpyunOSSProperty getProperty() {
        return property;
    }

    public void setProperty(CloudStorageConfig.UpyunOSSProperty property) {
        this.property = property;
    }

    CloudStorageConfig.UpyunOSSProperty property;


    public void init(String bucketName) {
        bucketName = Optional.ofNullable(bucketName).orElse(property.getUpyunBucketName());
        if (StringUtils.isNullOrEmpty(bucketName)) {
            throw new RuntimeException("未获取到bucketName");
        }
        uploadManager = new RestManager(bucketName, property.getUpyunAccessKey(), property.getUpyunSecretKey());

    }

    @Override
    public String upload(byte[] data, String path) {

        uploadManager.setTimeout(60 * 1000);
        uploadManager.setApiDomain(RestManager.ED_AUTO);

        try {
            //如果没指定名称则由生成随机
            if (uploadManager.getFileInfo(path).isSuccessful()) {
                throw new RuntimeException("已存在");
            }

            uploadManager.mkDir(path.substring(0, path.lastIndexOf('/')));

            final Map<String, String> paramsMap = new HashMap<String, String>();
            Response response = uploadManager.writeFile(path, data, paramsMap);

            if (response.isSuccessful()) {
                return path;
            } else {
                return "";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }

    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] var4;
            try {
                byte[] buffer = new byte[4096];

                while (true) {
                    int n;
                    if (-1 == (n = inputStream.read(buffer))) {
                        var4 = output.toByteArray();
                        break;
                    }

                    output.write(buffer, 0, n);
                }
            } catch (Throwable var6) {
                try {
                    output.close();
                } catch (Throwable var5) {
                    var6.addSuppressed(var5);
                }

                throw var6;
            }

            output.close();

            return this.upload(var4, path);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败");
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath("", suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath("", suffix));
    }

    @Override
    public String getDownloadUrl(Map<String, Object> map) {
        return getProperty().getUpyunDomain() + "/" + map.get("key");
    }
}
